// 全局变量
let codeEditor;
let socket;
let isDebugging = false;
let currentBreakpoints = new Set();

// 示例代码
const exampleCode = `# Python 调试器示例代码
def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

# 计算斐波那契数列
numbers = []
for i in range(6):
    fib_num = fibonacci(i)
    numbers.append(fib_num)
    print(f"fibonacci({i}) = {fib_num}")

# 计算总和
total = sum(numbers)
print(f"总和: {total}")

# 创建字典
result = {
    'numbers': numbers,
    'total': total,
    'average': total / len(numbers)
}

print("结果:", result)`;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeCodeEditor();
    initializeSocketConnection();
    bindEventListeners();
    showMessage('欢迎使用 WebOJ Python 调试器！', 'success');
});

// 初始化代码编辑器
function initializeCodeEditor() {
    const textarea = document.getElementById('codeEditor');
    codeEditor = CodeMirror.fromTextArea(textarea, {
        mode: 'python',
        theme: 'monokai',
        lineNumbers: true,
        indentUnit: 4,
        lineWrapping: true,
        gutters: ['CodeMirror-linenumbers', 'breakpoint-gutter'],
        extraKeys: {
            'F9': toggleBreakpoint,
            'F5': startDebug,
            'F10': stepExecution,
            'F11': continueExecution
        }
    });

    // 设置编辑器高度
    codeEditor.setSize(null, '400px');

    // 添加断点点击事件
    codeEditor.on('gutterClick', function(cm, n) {
        toggleBreakpoint(cm, n + 1);
    });

    // 加载示例代码
    codeEditor.setValue(exampleCode);
}

// 初始化Socket连接
function initializeSocketConnection() {
    socket = io();

    socket.on('connect', function() {
        updateConnectionStatus(true);
        showMessage('已连接到调试服务器', 'success');
    });

    socket.on('disconnect', function() {
        updateConnectionStatus(false);
        showMessage('与调试服务器断开连接', 'error');
    });

    socket.on('state_update', function(data) {
        updateDebugState(data);
    });

    socket.on('error', function(data) {
        showMessage(`调试错误: ${data.message}`, 'error');
        if (data.line) {
            highlightErrorLine(data.line);
        }
    });
}

// 绑定事件监听器
function bindEventListeners() {
    // 调试控制按钮
    document.getElementById('startDebug').addEventListener('click', startDebug);
    document.getElementById('stepBtn').addEventListener('click', stepExecution);
    document.getElementById('continueBtn').addEventListener('click', continueExecution);
    document.getElementById('stopDebug').addEventListener('click', stopDebug);

    // 头部控制按钮
    document.getElementById('loadExample').addEventListener('click', loadExample);
    document.getElementById('clearCode').addEventListener('click', clearCode);

    // 变量刷新按钮
    document.getElementById('refreshVars').addEventListener('click', refreshVariables);

    // 断点管理
    document.getElementById('addBreakpoint').addEventListener('click', addBreakpoint);
    document.getElementById('breakpointLine').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            addBreakpoint();
        }
    });

    // 输出面板标签切换
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            switchTab(this.dataset.tab);
        });
    });

    // 清空输出
    document.getElementById('clearOutput').addEventListener('click', clearOutput);
}

// 开始调试
async function startDebug() {
    const code = codeEditor.getValue().trim();
    if (!code) {
        showMessage('请输入要调试的代码', 'warning');
        return;
    }

    try {
        const response = await fetch('/api/start_debug', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ code: code })
        });

        const result = await response.json();
        
        if (response.ok) {
            isDebugging = true;
            updateDebugButtons(true);
            updateDebugStatus('调试中...');
            showMessage('调试器启动成功', 'success');
            clearOutput();
        } else {
            showMessage(`启动失败: ${result.error}`, 'error');
        }
    } catch (error) {
        showMessage(`网络错误: ${error.message}`, 'error');
    }
}

// 单步执行
async function stepExecution() {
    if (!isDebugging) return;

    try {
        const response = await fetch('/api/step', {
            method: 'POST'
        });

        const result = await response.json();
        
        if (response.ok) {
            updateDebugState(result);
        } else {
            showMessage(`单步执行失败: ${result.error}`, 'error');
        }
    } catch (error) {
        showMessage(`网络错误: ${error.message}`, 'error');
    }
}

// 继续执行
async function continueExecution() {
    if (!isDebugging) return;

    try {
        const response = await fetch('/api/continue', {
            method: 'POST'
        });

        const result = await response.json();
        
        if (response.ok) {
            updateDebugState(result);
        } else {
            showMessage(`继续执行失败: ${result.error}`, 'error');
        }
    } catch (error) {
        showMessage(`网络错误: ${error.message}`, 'error');
    }
}

// 停止调试
async function stopDebug() {
    try {
        const response = await fetch('/api/stop_debug', {
            method: 'POST'
        });

        if (response.ok) {
            isDebugging = false;
            updateDebugButtons(false);
            updateDebugStatus('调试器未启动');
            clearCurrentLineHighlight();
            showMessage('调试器已停止', 'success');
        }
    } catch (error) {
        showMessage(`网络错误: ${error.message}`, 'error');
    }
}

// 切换断点
function toggleBreakpoint(cm, lineNumber) {
    if (typeof cm === 'number') {
        lineNumber = cm;
    }

    if (currentBreakpoints.has(lineNumber)) {
        removeBreakpointFromLine(lineNumber);
    } else {
        setBreakpointOnLine(lineNumber);
    }
}

// 在指定行设置断点
async function setBreakpointOnLine(lineNumber) {
    try {
        const response = await fetch('/api/set_breakpoint', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ line_number: lineNumber })
        });

        const result = await response.json();
        
        if (response.ok) {
            currentBreakpoints.add(lineNumber);
            updateBreakpointGutter(lineNumber, true);
            updateBreakpointsList(result.breakpoints);
            showMessage(`断点已设置在第 ${lineNumber} 行`, 'success');
        } else {
            showMessage(`设置断点失败: ${result.error}`, 'error');
        }
    } catch (error) {
        showMessage(`网络错误: ${error.message}`, 'error');
    }
}

// 移除指定行的断点
async function removeBreakpointFromLine(lineNumber) {
    try {
        const response = await fetch('/api/remove_breakpoint', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ line_number: lineNumber })
        });

        const result = await response.json();
        
        if (response.ok) {
            currentBreakpoints.delete(lineNumber);
            updateBreakpointGutter(lineNumber, false);
            updateBreakpointsList(result.breakpoints);
            showMessage(`断点已从第 ${lineNumber} 行移除`, 'success');
        } else {
            showMessage(`移除断点失败: ${result.error}`, 'error');
        }
    } catch (error) {
        showMessage(`网络错误: ${error.message}`, 'error');
    }
}

// 添加断点（通过输入框）
function addBreakpoint() {
    const input = document.getElementById('breakpointLine');
    const lineNumber = parseInt(input.value);
    
    if (isNaN(lineNumber) || lineNumber < 1) {
        showMessage('请输入有效的行号', 'warning');
        return;
    }

    const totalLines = codeEditor.lineCount();
    if (lineNumber > totalLines) {
        showMessage(`行号不能超过 ${totalLines}`, 'warning');
        return;
    }

    setBreakpointOnLine(lineNumber);
    input.value = '';
}

// 刷新变量信息
async function refreshVariables() {
    if (!isDebugging) {
        showMessage('请先启动调试器', 'warning');
        return;
    }

    try {
        const response = await fetch('/api/get_variables');
        const result = await response.json();
        
        if (response.ok) {
            updateVariablesDisplay(result.variables);
        } else {
            showMessage(`获取变量失败: ${result.error}`, 'error');
        }
    } catch (error) {
        showMessage(`网络错误: ${error.message}`, 'error');
    }
}

// 更新调试状态
function updateDebugState(state) {
    if (state.current_line) {
        highlightCurrentLine(state.current_line);
        updateCurrentLineInfo(state.current_line, state.total_lines);
    }

    if (state.variables) {
        updateVariablesDisplay(state.variables);
    }

    if (state.breakpoints) {
        updateBreakpointsList(state.breakpoints);
    }

    if (state.output) {
        updateOutput(state.output);
    }

    if (state.errors) {
        updateErrors(state.errors);
    }

    // 更新执行模式显示
    if (state.step_mode !== undefined) {
        updateExecutionMode(state.step_mode);
    }

    if (state.is_finished) {
        isDebugging = false;
        updateDebugButtons(false);
        updateDebugStatus('调试完成');
        clearCurrentLineHighlight();
        showMessage('程序执行完成', 'success');
    }
}

// 高亮当前执行行
function highlightCurrentLine(lineNumber) {
    clearCurrentLineHighlight();
    codeEditor.addLineClass(lineNumber - 1, 'background', 'CodeMirror-line-highlight');
}

// 清除当前行高亮
function clearCurrentLineHighlight() {
    for (let i = 0; i < codeEditor.lineCount(); i++) {
        codeEditor.removeLineClass(i, 'background', 'CodeMirror-line-highlight');
    }
}

// 高亮错误行
function highlightErrorLine(lineNumber) {
    codeEditor.addLineClass(lineNumber - 1, 'background', 'error-line');
    setTimeout(() => {
        codeEditor.removeLineClass(lineNumber - 1, 'background', 'error-line');
    }, 3000);
}

// 更新断点装订线
function updateBreakpointGutter(lineNumber, hasBreakpoint) {
    const marker = hasBreakpoint ? '●' : '';
    codeEditor.setGutterMarker(lineNumber - 1, 'breakpoint-gutter', 
        hasBreakpoint ? makeMarker() : null);
}

// 创建断点标记
function makeMarker() {
    const marker = document.createElement('div');
    marker.className = 'breakpoint-marker';
    marker.innerHTML = '●';
    return marker;
}

// 更新变量显示
function updateVariablesDisplay(variables) {
    const container = document.getElementById('variablesContainer');
    
    if (!variables || Object.keys(variables).length === 0) {
        container.innerHTML = '<p class="no-data">暂无变量信息</p>';
        return;
    }

    let html = '';
    for (const [name, info] of Object.entries(variables)) {
        html += `
            <div class="variable-item">
                <div class="variable-name">${name}</div>
                <div class="variable-value">${info.value}</div>
                <div class="variable-type">${info.type}</div>
            </div>
        `;
    }
    
    container.innerHTML = html;
}

// 更新断点列表
function updateBreakpointsList(breakpoints) {
    const container = document.getElementById('breakpointsContainer');
    
    if (!breakpoints || breakpoints.length === 0) {
        container.innerHTML = '<p class="no-data">暂无断点</p>';
        return;
    }

    let html = '';
    breakpoints.forEach(line => {
        html += `
            <div class="breakpoint-item">
                <span class="breakpoint-line">第 ${line} 行</span>
                <button class="remove-breakpoint" onclick="removeBreakpointFromLine(${line})">×</button>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 更新当前行信息
function updateCurrentLineInfo(currentLine, totalLines) {
    const info = document.getElementById('currentLineInfo');
    info.textContent = `当前行: ${currentLine} / ${totalLines}`;
}

// 更新执行模式显示
function updateExecutionMode(stepMode) {
    const statusElement = document.getElementById('debugStatus');
    if (stepMode) {
        statusElement.textContent = '调试中 (单步模式)';
        statusElement.style.color = '#48bb78'; // 绿色
    } else {
        statusElement.textContent = '调试中 (继续执行)';
        statusElement.style.color = '#4299e1'; // 蓝色
    }
}

// 更新调试状态
function updateDebugStatus(status) {
    const statusElement = document.getElementById('debugStatus');
    statusElement.textContent = status;
    statusElement.style.color = ''; // 重置颜色
}

// 更新调试按钮状态
function updateDebugButtons(debugging) {
    document.getElementById('startDebug').disabled = debugging;
    document.getElementById('stepBtn').disabled = !debugging;
    document.getElementById('continueBtn').disabled = !debugging;
    document.getElementById('stopDebug').disabled = !debugging;
}

// 切换输出标签
function switchTab(tabName) {
    // 更新标签按钮状态
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');

    // 更新内容显示
    document.querySelectorAll('.tab-content').forEach(content => {
        content.classList.remove('active');
    });
    document.getElementById(`${tabName}Content`).classList.add('active');
}

// 更新输出内容
function updateOutput(output) {
    const container = document.getElementById('outputContent');
    container.textContent = output || '';
    container.scrollTop = container.scrollHeight;
}

// 更新错误信息
function updateErrors(errors) {
    const container = document.getElementById('errorsContent');
    container.textContent = errors || '';
    container.scrollTop = container.scrollHeight;
}

// 清空输出
function clearOutput() {
    document.getElementById('outputContent').textContent = '';
    document.getElementById('errorsContent').textContent = '';
}

// 加载示例代码
function loadExample() {
    codeEditor.setValue(exampleCode);
    showMessage('示例代码已加载', 'success');
}

// 清空代码
function clearCode() {
    if (confirm('确定要清空所有代码吗？')) {
        codeEditor.setValue('');
        showMessage('代码已清空', 'success');
    }
}

// 显示消息提示
function showMessage(message, type = 'info') {
    const container = document.getElementById('messageContainer');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${type}`;
    messageDiv.textContent = message;
    
    container.appendChild(messageDiv);
    
    // 3秒后自动移除消息
    setTimeout(() => {
        if (messageDiv.parentNode) {
            messageDiv.parentNode.removeChild(messageDiv);
        }
    }, 3000);
}

// 键盘快捷键处理
document.addEventListener('keydown', function(e) {
    if (e.key === 'F5') {
        e.preventDefault();
        if (!isDebugging) {
            startDebug();
        }
    } else if (e.key === 'F9') {
        e.preventDefault();
        const cursor = codeEditor.getCursor();
        toggleBreakpoint(cursor.line + 1);
    } else if (e.key === 'F10') {
        e.preventDefault();
        if (isDebugging) {
            stepExecution();
        }
    } else if (e.key === 'F11') {
        e.preventDefault();
        if (isDebugging) {
            continueExecution();
        }
    }
});

// 更新连接状态
function updateConnectionStatus(connected) {
    const status = document.getElementById('connectionStatus');
    status.textContent = connected ? '�� 已连接' : '🔴 未连接';
} 